# -*- coding: utf-8 -*-
"""
Created on Sat Nov  4 17:04:09 2017

@author: Luther
"""

import requests
import re
import json
import pandas as pd
from datetime import date


def getStock_ori(code):

    try:
        r = requests.get(
            'https://finance.yahoo.com/quote/{}/history?period1=1451577600&period2=1483113600&interval=1d&filter=history&frequency=1d'.
            format(code))
        r.raise_for_status
        r.encoding = r.apparent_encoding
        m = re.findall('"HistoricalPriceStore":{"prices":(.*?),"isPending"',
                       r.text)
        if m:
            quotes = json.loads(m[0])
            quotes = quotes[::-1]
        return [item for item in quotes if not 'type' in item]
    except:
        print('error!')


def getStock(quotes):

    list1 = []
    for i in range(len(quotes)):
        x = date.fromtimestamp(quotes[i]['date'])
        y = date.strftime(x, '%Y-%m-%d')
        list1.append(y)
    quotesdf_ori = pd.DataFrame(quotes, index=list1)
    quotesdf = quotesdf_ori.drop(['date'], axis=1)
    quotesdf = quotesdf[1:]
    return quotesdf


def main():
    code = input('Please input code:')
    quotes = getStock_ori(code)
    quotesdf = getStock(quotes)
    print(quotesdf[:len(quotesdf):7])


main()
